<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 18-9-25
 * Time: 下午4:37
 */

namespace App\Utility\Pool;


use EasySwoole\Component\Pool\PoolObjectInterface;
use EasySwoole\Mysqli\Mysqli;

class MysqlPoolObject extends Mysqli implements PoolObjectInterface
{

    function gc()
    {
        $this->resetDbStatus();
        $this->getMysqlClient()->close();
    }

    function objectRestore()
    {
        $this->resetDbStatus();
    }

    function beforeUse(): bool
    {
        // TODO: Implement beforeUse() method.
        //使用前调用,当返回true，表示该对象可用。返回false，该对象失效，需要回收
        //根据个人逻辑修改,只要做好了断线处理逻辑,就可直接返回true
        return $this->getMysqlClient()->connected;
    }

    /**
     * 批量更新
     * @param $data array 待更新的数据，二维数组格式
     * @param array $params array 值相同的条件，键值对应的一维数组
     * @param string $field string 值不同的条件，默认为id
     * @return bool|string
     */
    function batchUpdate( $tableName, $data, $field, $params = [] )
    {
        if ( !is_array( $data ) || !$field || !is_array( $params ) ) {
            return false;
        }

        $updates = $this->parseUpdate( $data, $field );
        $where = $this->parseParams( $params );

        // 获取所有键名为$field列的值，值两边加上单引号，保存在$fields数组中
        // array_column()函数需要PHP5.5.0+，如果小于这个版本，可以自己实现，
        $fields = array_column( $data, $field );
        $fields = implode( ',', array_map( function ( $value ) {
            return "'" . $value . "'";
        }, $fields ) );

        $sql = sprintf( "UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $tableName, $updates, $field, $fields, $where );

        return $sql;
    }

    /**
     * 将二维数组转换成CASE WHEN THEN的批量更新条件
     * @param $data array 二维数组
     * @param $field string 列名
     * @return string sql语句
     */
    protected function parseUpdate( $data, $field )
    {
        $sql = '';
        $keys = array_keys( current( $data ) );
        foreach ( $keys as $column ) {
            if ( $column == $field ) {
                continue;
            }
            $sql .= sprintf( "`%s` = CASE `%s` ", $column, $field );
            foreach ( $data as $line ) {
                $sql .= sprintf( "WHEN '%s' THEN %s ", $line[ $field ], $line[ $column ] );
            }
            $sql .= "END,";
        }

        return rtrim( $sql, ',' );
    }

    /**
     * 解析where条件
     * @param $params
     * @return array|string
     */
    protected function parseParams( $params )
    {
        $where = [];
        foreach ( $params as $key => $value ) {
            $where[] = sprintf( "`%s` = '%s'", $key, $value );
        }

        return $where ? ' AND ' . implode( ' AND ', $where ) : '';
    }



}